package com.example.demo.controller;

import com.example.demo.entity.UserEntity;
import com.example.demo.jpa.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author ml
 * @create 2017-07-07--16:25
 */
@RestController
public class UserController {

    @Autowired
    private UserJpa userJpa;


    @RequestMapping(value = "/list")
    public List<UserEntity> list() {
        return userJpa.findAll();
    }

    @RequestMapping(value = "/add")
    public String add() {
        UserEntity user = new UserEntity();
        user.setName("Maxiaolin");
        user.setAge(0);
        user.setAddress("Xinyi");
        userJpa.save(user);
        return "信息添加成功！";
    }

    @RequestMapping(value = "/delete")
    public String delete(Long userid) {

        userJpa.delete(userid);

        return "用户信息删除成功";

    }

    @RequestMapping(value = "/age")
    public List<UserEntity> age(int age) {
        return userJpa.nativeQuery(age);
    }

    @Transactional
    @RequestMapping(value = "/deleteQuery")
    public String delete() {
        userJpa.deleteQuery("Admin", "123");
        return "自定义删除成功";
    }

    /**
     * 分页查询测试
     * @param page
     * @return
     */

    @RequestMapping(value = "/cutPage")
    public List<UserEntity> cutPage(int page){
        UserEntity user=new UserEntity();
        user.setSize(2);
        user.setPage(page);
        user.setSord("asc");

        //获取排序对象
        Sort.Direction sort_direction = Sort.Direction.ASC.toString().equalsIgnoreCase(user.getSord())?Sort.Direction.ASC:Sort.Direction.DESC;

        //设置排序对象参数
        Sort sort=new Sort(sort_direction,user.getSidx());
        //创建分页对象
        PageRequest pageRequest=new PageRequest(user.getPage()-1,user.getSize(),sort);
        //执行分页查询
        return  userJpa.findAll(pageRequest).getContent();
    }

}
